using System.Reflection;
using rpc_service.cache;
using rpc_service.core.interceptor;
using rpc_service.log;
using Microsoft.Extensions.Logging;

namespace rpc_service.core.support;

public class RPCClassLoader
{
    private readonly ILogger<RPCClassLoader> _logger = Logger.GetLoggerFactory().CreateLogger<RPCClassLoader>();

    private List<Type> _classList = new List<Type>();
    private List<Type> _interceptors = new List<Type>();
    
    /// <summary>
    /// 将所有的 RPC 类加载出来
    /// </summary>
    /// <returns></returns>
    public List<Type> ClassLoader()
    {
        if (_classList.Count != 0)
        {
            return _classList;
        }
        
        Assembly assembly = Assembly.GetExecutingAssembly();
        Type[] types = assembly.GetTypes();
        _classList = new List<Type>();
        
        _logger.LogInformation("开始读取 RPC 类");
        
        foreach (Type type in types)
        {
            // 如果是接口 同时拥有 RPCClass 注解
            // 就取出来存放
            if (type.IsInterface && type.GetCustomAttribute<RPCClass>() != null)
            {
                _classList.Add(type);
            }
        }

        return _classList;
    }

    public List<Type> InterceptorClassLoader() 
    { 
        if (_interceptors.Count != 0) 
        { 
            return _interceptors; 
        }
    
        Assembly assembly = Assembly.GetExecutingAssembly(); 
        Type[] types = assembly.GetTypes(); 
        _interceptors = new List<Type>(); 
    
        _logger.LogInformation("开始读取 拦截器 类"); 
    
        foreach (Type type in types) 
        { 
            // 检查类型是否实现了 Interceptor 接口，并且不是接口或抽象类
            if (!type.IsInterface && !type.IsAbstract && 
                "Interceptor".GetTypeByStr().IsAssignableFrom(type)) 
            { 
                try
                {
                    // 创建拦截器实例并添加到列表
                    _interceptors.Add(type);
                    _logger.LogInformation($"已加载拦截器: {type.FullName}");
                }
                catch (Exception ex)
                {
                    _logger.LogError($"创建拦截器 {type.FullName} 实例失败: {ex.Message}");
                }
            } 
        } 

        return _interceptors; 
    }
    
}